package emergency;

import java.util.ArrayList;

import unit.*;

public class RequirementsPublicDisturbance extends RequirementsEmergency {

	/**
	 * Checks if this requirement is the right one to handle the given emergency
	 * 
	 * @param emergency
	 *            the emergency to check if this Requirement needs to handle it
	 * 
	 * @return Returns true if this is the right requirement for the given
	 *         emergency, false if not
	 */
	@Override
	boolean canHandleEmergency(Emergency emergency) {
		return (emergency instanceof PublicDisturbance);
	}

	/**
	 * Method that will create the suggestion for the given emergency, with the
	 * given units
	 * 
	 * @param emergency
	 *            the emergency we need to compute the suggestion for
	 * 
	 * @param units
	 *            list of units of which the needed units will be picked
	 * 
	 * @return Returns a list of suggested units to assign to the emergency
	 * 
	 * @throws IllegalArgumentException
	 *             not enough units are available in the given unit list
	 */
	@Override
	ArrayList<Unit> createSuggestion(Emergency emergency, ArrayList<Unit> units) {
		if (canHandleEmergency(emergency)) {
			ArrayList<Unit> suggestedUnits = new ArrayList<Unit>();
			setRequirements(emergency);

			int pol = getTotalPoliceCarsNeeded();

			for (Unit u : units) {
				if (u instanceof PoliceCar) {
					if (pol > 0) {
						suggestedUnits.add(u);
						pol--;
					}
				}
			}

			emergency.setEmergencyRequirements(this);

			if (pol == 0)
				return suggestedUnits;

			else
				throw new IllegalArgumentException(
						"Not enough units given to handle this emergency");

		} else {
			return getNextInChain().createSuggestion(emergency, units);
		}
	}

	/**
	 * Method for setting the total units needed, depending on this requirement
	 * 
	 * @post The total amount of ambulances needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of policecars needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of firetrucks needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of units needed is set, depending on this
	 *       requirement
	 */
	@Override
	void setRequirements(Emergency emergency) {
		if (canHandleEmergency(emergency)) {
			emergency.setEmergencyRequirements(this);

			PublicDisturbance publicDisturbance = (PublicDisturbance) emergency;

			int alreadyAssigned = amountOfAssignedUnits("PoliceCar",
					emergency.getUnitsClone());

			double x = (double) publicDisturbance.getNumberOfPeople() / 5;
			setTotalPoliceCarsNeeded(diff((int) Math.ceil(x), alreadyAssigned));

			setTotalFireTrucksNeeded(0);
			setTotalAmbulancesNeeded(0);

			setTotalUnitsNeeded(getTotalPoliceCarsNeeded());
		} else
			getNextInChain().setRequirements(emergency);

	}
}
